package com.qianfeng.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionUtils {
    static SqlSession sqlSession;
    private SqlSessionUtils(){
    }
    private static final SqlSessionUtils sqlsessionutils=new SqlSessionUtils();
    public static SqlSessionUtils getInstance(){
        return sqlsessionutils;
    }
    public <T> T conn(Class<T> classDao) throws IOException {
        //通过流加载mybatis.xml
        InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
        //建立数据库连接，创建一个sql会话工厂构建类，参数放流，构建一个会话工厂
        SqlSessionFactoryBuilder sfb=new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory = sfb.build(inputStream);
        //从会话工厂中获取sql会话
        sqlSession = sessionFactory.openSession();
        //通过Mapper加载类，返回一个实现类
        return sqlSession.getMapper(classDao);
    }
    public void close(){
        sqlSession.close();
    }
    public void commit(){
        sqlSession.commit();
    }
}
